package com.huawei.hmsdemo10086.Activity;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.Image;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.huawei.hms.hwid.I;
import com.huawei.hmsdemo10086.Adapter.PayAdapter;
import com.huawei.hmsdemo10086.POJO.Address;
import com.huawei.hmsdemo10086.POJO.Car;
import com.huawei.hmsdemo10086.POJO.Goods;
import com.huawei.hmsdemo10086.POJO.Result;
import com.huawei.hmsdemo10086.R;

import java.io.IOException;
import java.io.Serializable;
import java.lang.reflect.Type;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class PayActivity extends AppCompatActivity {

    private static Goods goods;
    private Address address;
    private ImageView pay_goos_img;
    private TextView pay_goods_name;
    private TextView num_text;
    private TextView pay_goods_price;
    private TextView pay_totol;
    private Button pay_buy_button;
    private int num;
    private String userId;
    private SharedPreferences sharedPreferences;
    private List<Car> cars;
    private PayAdapter payAdapter;
    private ListView listView;
    private int orderid;
    private int flag = 1;
    private double tot = 0;
    private double point = 0;
    private Result<Float> point_res = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pay);

        TextView mTitleTextView = (TextView) this.findViewById(R.id.text_title);
        mTitleTextView.setText("支付订单");
        Button back = (Button)this.findViewById(R.id.button_backward);
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(PayActivity.this,CarActivity.class);
                startActivity(intent);
                finish();
            }
        });

        flag = 1;
        sharedPreferences = getSharedPreferences("userInfo", Context.MODE_PRIVATE);
        userId = sharedPreferences.getString("userId",null);
        point = sharedPreferences.getFloat("point",0);
        address = (Address) getIntent().getSerializableExtra("address");
        cars = (List<Car>)getIntent().getSerializableExtra("cars");
        listView = (ListView)findViewById(R.id.car_list);

        for(int i = 0 ; i < cars.size() ; i++)
        {
            tot += cars.get(i).getNum()*cars.get(i).getGoods().getPrice();
        }


        if(address!=null){
            TextView address_text = findViewById(R.id.address_text);
            TextView phone_text = findViewById(R.id.phone_text);
            TextView address_name = findViewById(R.id.address_name);
            TextView address_region = findViewById(R.id.address_region);
            address_text.setText(address.getAddress());
            phone_text.setText(address.getPhone());
            address_name.setText(address.getName());
            address_region.setText(address.getRegion());
        }
        initView();
        LinearLayout linearLayout = findViewById(R.id.choose_address_layout);
        linearLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(PayActivity.this,AddressActivity.class);
                intent.putExtra("tag",1);
//                intent.putExtra("goods",goods);
//                intent.putExtra("num",num);
                intent.putExtra("cars",(Serializable)cars);
                startActivity(intent);
            }
        });
    }

    private void initView() {
        pay_buy_button = findViewById(R.id.pay_buy_button);
        pay_totol = findViewById(R.id.pay_totol);
        payAdapter = new PayAdapter(PayActivity.this, cars);

        Log.d("initView", listView==null?"null":"no");
        Log.d("initView", payAdapter==null?"null":"no");
        Log.d("initView", cars==null?"null":"no");

        listView.setAdapter(payAdapter);
        payAdapter.notifyDataSetChanged();
        pay_totol.setText(String.valueOf(tot));
//        pay_goods_name.setText(goods.getName());
//        Glide.with(this).load(goods.getPicaddress()).into(pay_goos_img);
//        pay_goods_name.setText(goods.getName());
//        pay_goods_price.setText(goods.getPrice()+"");
//        pay_totol.setText(goods.getPrice()*num+"");
//        num_text.setText(""+num);


        pay_buy_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(address==null){
                    Toast.makeText(PayActivity.this, "地址没填", Toast.LENGTH_SHORT).show();
                }else if(point<tot){
                    Toast.makeText(PayActivity.this, "没钱", Toast.LENGTH_SHORT).show();
                }else{
                    submitUserCar();
                    AlertDialog.Builder builder = new AlertDialog.Builder(PayActivity.this);
                    builder.setTitle("支付成功");
                    builder.setNegativeButton("回到首页", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            Intent intent = new Intent(PayActivity.this,MainActivity.class);
                            startActivity(intent);
                        }
                    });
                    builder.show();
                    pay();
                }

            }
        });
    }



    private void submitUserCar()
    {

        for(int i = 0 ; i < cars.size() ; i++)
        {
            while(flag == 0)
            {
                System.out.println("1111111111111111111111111");
            }
            if(i == 0)
            {
                flag = 0;
                String url = "http://10.0.2.2:8443/api/insertOrder";
                OkHttpClient mOkHttpClient = new OkHttpClient();

                String json = "{\n" +
                        "  \"addressid\": \"" + address.getAddressid() + "\",\n" +
                        "  \"goodsid\": \"" + cars.get(i).getGoodsid()+ "\",\n" +
                        "  \"num\": \"" + cars.get(i).getNum() + "\",\n" +
                        "  \"userid\": \"" + userId + "\"\n" +
                        "}";

                Request request = new Request.Builder().url(url).post(RequestBody.create(MediaType.parse("application/json"),json)).build();

                mOkHttpClient.newCall(request).enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        Log.e("测试", e+"");
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        Gson gson = new Gson();
                        String rep = response.body().string();
                        Type type = new TypeToken<Result<Integer>>(){}.getType();
                        Result<Integer> result = gson.fromJson(rep,type);
                        orderid = result.getData();
                        System.out.println(orderid);
                        flag = 1;
                    }
                });
            }
            else
            {
                flag = 0;
                String url = "http://10.0.2.2:8443/api/insertOrderAndId";
                OkHttpClient mOkHttpClient = new OkHttpClient();

                String json = "{\n" +
                        "  \"addressid\": \"" + address.getAddressid() + "\",\n" +
                        "  \"goodsid\": \"" + cars.get(i).getGoodsid()+ "\",\n" +
                        "  \"orderid\": \"" + orderid+ "\",\n" +
                        "  \"num\": \"" + cars.get(i).getNum() + "\",\n" +
                        "  \"userid\": \"" + userId + "\"\n" +
                        "}";

                Request request = new Request.Builder().url(url).post(RequestBody.create(MediaType.parse("application/json"),json)).build();

                mOkHttpClient.newCall(request).enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        Log.e("测试", e+"");
                    }
                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        flag = 1;
                    }
                });
            }

        }
    }


    public void pay()
    {
        String url = "http://10.0.2.2:8443/api/payBill";
        OkHttpClient mOkHttpClient = new OkHttpClient();

        String json = "{\n" +
                "  \"totle_price\": \"" + tot+ "\",\n" +
                "  \"userid\": \"" + userId + "\"\n" +
                "}";

        Request request = new Request.Builder().url(url).post(RequestBody.create(MediaType.parse("application/json"),json)).build();

        mOkHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("测试", e+"");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Gson gson = new Gson();
                String rep = response.body().string();

                Type type = new TypeToken<Result<Float>>(){}.getType();
                point_res = gson.fromJson(rep,type);
                Log.d("point", point_res.getData()+"");
                SharedPreferences.Editor editor = sharedPreferences.edit();
                editor.putFloat("point",(float) point_res.getData());
                editor.commit();

            }
        });
    }



}